package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.StrategyCatalogQuery;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/travel")
public class TravelController {

    @Reference
    private IRegionService regionService;

    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    @RequestMapping("")
    public String travels(@ModelAttribute("qo")TravelQuery qo, Model model){
        // pageInfo
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        // tcs -- 回复游记的最新动态前10显示
        List<TravelComment> travelComments = travelCommentService.OrderByCreateTimeTop10();
        model.addAttribute("tcs", travelComments);

        // 查询国内最火的前10攻略显示(按照阅读量最高前10个)
        List<StrategyStatisVO> vos = strategyStatisVORedisService.listHotVOTop10();
        System.out.println(vos);
        model.addAttribute("vos", vos);

        return "travel/list";
    }

    @RequestMapping("/commentAdd")
    public String commentAdd(TravelComment travelComment, Model model, @UserParam UserInfo userInfo){
        travelComment.setUsername(userInfo.getNickname());
        travelComment.setUserId(userInfo.getId());
        travelComment.setCity(userInfo.getCity());
        travelComment.setLevel(userInfo.getLevel());
        travelComment.setHeadUrl(userInfo.getHeadImgUrl());

        TravelComment comment = travelCommentService.saveOrUpdate(travelComment); // 返回 TravelComment 为了解决分布式服务
        model.addAttribute("c", comment);
        long floor = travelCommentService.getCount(travelComment.getTravelId());
        model.addAttribute("floor", floor + 1);

        // STRATEGY_STATIS_VO
        // sid
        // STRATEGY_ZSET_SORT_COMMEND
        // score
//        RedisKeys.
//        strategyStatisVORedisService.addTravelCommentScore();
        return "/travel/commentTpl";
    }

    @RequestMapping("/detail")
    public String detail(Long id, Model model){
        // list
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setPageSize(Integer.MAX_VALUE);
        List content = travelCommentService.query(qo).getContent();
        model.addAttribute("list", content);
        // detail
        Travel travel = travelService.get(id);
        travel.setTravelContent(travelService.getContent(id)); // 注意：此处不直接在 get 方法内处理内容相关，是为了好维护

        model.addAttribute("detail", travel);
        // toasts
        Long destId = travel.getDest().getId();
        model.addAttribute("toasts", destinationService.getToasts(destId));
        // sds
        model.addAttribute("sds", strategyDetailService.getViewNumTop3(destId));
        // ts
        model.addAttribute("ts", travelService.getViewNumTop3(destId));
        return "/travel/detail";
    }

    @RequestMapping("input")
    public String input(Long id, Model model){
        if(id != null){
            // tv 回显
            Travel travel = travelService.get(id);
            travel.setTravelContent(travelService.getContent(id)); // 注意：此处不直接在 get 方法内处理内容相关，是为了好维护
            model.addAttribute("tv", travel);
        }
        // dests
        model.addAttribute("dests", destinationService.list());
        return "travel/input";
    }







    @Value("${file.path}")
    private String filePath;

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo){
        if(travel.getAuthor().getId() == null){
            travel.setAuthor(userInfo);
        }
        Long travelId = travelService.saveOrUpdate(travel, userInfo);
        return AjaxResult.SUCCESS.addData(travelId);
    }






}
